package com.java110.acct.payment.adapt.pxlc;

import com.alibaba.fastjson.JSONObject;
import com.java110.acct.payment.IRefundMoneyAdapt;
import com.java110.acct.payment.adapt.pxlc.utils.HttpConnectUtils;
import com.java110.core.client.FtpUploadTemplate;
import com.java110.core.client.OssUploadTemplate;
import com.java110.core.factory.GenerateCodeFactory;
import com.java110.core.factory.WechatFactory;
import com.java110.core.log.LoggerFactory;
import com.java110.dto.onlinePayRefund.OnlinePayRefundDto;
import com.java110.dto.payment.PaymentPoolDto;
import com.java110.dto.payment.PaymentPoolValueDto;
import com.java110.dto.wechat.OnlinePayDto;
import com.java110.intf.acct.IOnlinePayRefundV1InnerServiceSMO;
import com.java110.intf.acct.IOnlinePayV1InnerServiceSMO;
import com.java110.intf.acct.IPaymentPoolValueV1InnerServiceSMO;
import com.java110.intf.fee.IReturnPayFeeInnerServiceSMO;
import com.java110.intf.order.IOrderInnerServiceSMO;
import com.java110.intf.store.ISmallWechatV1InnerServiceSMO;
import com.java110.utils.util.ListUtil;
import com.java110.utils.util.PayUtil;
import com.java110.vo.ResultVo;
import org.apache.commons.lang.RandomStringUtils;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Service("pxlcRefundMoney")
public class PxlcRefundMoneyAdapt implements IRefundMoneyAdapt {


    @Autowired
    private IPaymentPoolValueV1InnerServiceSMO paymentPoolValueV1InnerServiceSMOImpl;

    @Autowired
    private IReturnPayFeeInnerServiceSMO returnPayFeeInnerServiceSMOImpl;

    @Autowired
    private IOrderInnerServiceSMO orderInnerServiceSMOImpl;

    @Autowired
    private IOnlinePayV1InnerServiceSMO onlinePayV1InnerServiceSMOImpl;

    @Autowired
    private ISmallWechatV1InnerServiceSMO smallWechatV1InnerServiceSMOImpl;

    @Autowired
    private RestTemplate outRestTemplate;


    private static Logger logger = LoggerFactory.getLogger(PxlcRefundMoneyAdapt.class);

    private  static final SimpleDateFormat timeforamt=new SimpleDateFormat("yyyyMMddHHmmss");

    @Autowired
    private FtpUploadTemplate ftpUploadTemplate;

    @Autowired
    private OssUploadTemplate ossUploadTemplate;

    @Autowired
    private IOnlinePayRefundV1InnerServiceSMO onlinePayRefundV1InnerServiceSMOImpl;

    @Override
    public ResultVo refund(OnlinePayDto onlinePayDto, PaymentPoolDto paymentPoolDto) throws Exception {

        PaymentPoolValueDto paymentPoolValueDto = new PaymentPoolValueDto();
        paymentPoolValueDto.setPpId(paymentPoolDto.getPpId());
        List<PaymentPoolValueDto> paymentPoolValueDtos = paymentPoolValueV1InnerServiceSMOImpl.queryPaymentPoolValues(paymentPoolValueDto);

        if (paymentPoolValueDtos == null || paymentPoolValueDtos.isEmpty()) {
            throw new IllegalArgumentException("配置错误,未配置参数");
        }

        String ORGID = PaymentPoolValueDto.getValue(paymentPoolValueDtos, "ORGID"); // 客户编号
        String ORGMERCODE = PaymentPoolValueDto.getValue(paymentPoolValueDtos, "ORGMERCODE");
        String ORGTERMNO = PaymentPoolValueDto.getValue(paymentPoolValueDtos, "ORGTERMNO");
        String EASYPAY_PUBLIC_KEY = PaymentPoolValueDto.getValue(paymentPoolValueDtos, "EASYPAY_PUBLIC_KEY");
        String MD5_SING_KEY = PaymentPoolValueDto.getValue(paymentPoolValueDtos, "MER_RSA_PRIVATE_KEY");

        // todo 查询退费明细
        OnlinePayRefundDto onlinePayRefundDto = new OnlinePayRefundDto();
        onlinePayRefundDto.setPayId(onlinePayDto.getPayId());
        onlinePayRefundDto.setState(OnlinePayDto.STATE_WT);
        List<OnlinePayRefundDto> onlinePayRefundDtos = onlinePayRefundV1InnerServiceSMOImpl.queryOnlinePayRefunds(onlinePayRefundDto);
        String tranNo = GenerateCodeFactory.getGeneratorId("11");
        if (!ListUtil.isNull(onlinePayRefundDtos)) {
            tranNo = onlinePayRefundDtos.get(0).getRefundId();
        }

        JsApi request = new JsApi();
        request.setTxn_num("unified_refund"); // 小程序支付
        request.setVersion("3.0");
        request.setMch_create_ip("117.158.14.7"); // ip
        request.setDate_time(timeforamt.format(new Date()));
        request.setMcht_id(ORGID); // 商户号
        request.setDev_id(ORGTERMNO); // 终端号
        request.setNonce_str(RandomStringUtils.randomAlphabetic(12)); // 随机串

        request.setOut_order_no(onlinePayDto.getOrderId()); // 当前退款订单号
        request.setOut_refund_no(tranNo); // 商户退款订单号
        request.setOrg_fee(PayUtil.moneyToIntegerStr(Double.parseDouble(onlinePayDto.getRefundFee()))); // 原交易金额
        request.setRefund_fee(PayUtil.moneyToIntegerStr(Double.parseDouble(onlinePayDto.getRefundFee()))); // 退款金额
        request.setOp_user_id(ORGID); // 操作员帐号, 默认为商户号

        // 附加数据
        JsApi.HeadAttach head_attach = new JsApi.HeadAttach();
        head_attach.setDev_sp("landi");
        head_attach.setDev_model("E350G");
        head_attach.setLat("121.483527");
        head_attach.setLng("31.22134");
        head_attach.setDev_sn(ORGMERCODE);
        head_attach.setDev_version("liandiv3.2");
        head_attach.setStation("460|00|14382|44724|24|");
        request.setHead_attach(head_attach);

        request.setSign(BasePay.calMD5(JSONObject.toJSONString(request), MD5_SING_KEY));

        System.out.println("\n退款请求报文：" + JSONObject.toJSONString(request));
        String response = HttpConnectUtils.sendHttpSRequest(BasePay.BASE_URL, JSONObject.toJSONString(request), "JSON", null);
        System.out.println("\n退款响应报文：" + response);

        JSONObject paramOut = JSONObject.parseObject(response);

        if (!"000000".equals(paramOut.getString("return_code"))) {
            return new ResultVo(ResultVo.CODE_ERROR, "退款失败" + paramOut.getString("return_msg"));
        }
        return new ResultVo(ResultVo.CODE_OK, "退款完成");


    }


}
